package com.etbsms.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etbsms.dao.IResearchAndAnalysisDAO;
import com.etbsms.domain.AgricultureAndFood;
import com.etbsms.domain.CodeCountry;
import com.etbsms.domain.CodePlant;
import com.etbsms.domain.Files;
import com.etbsms.domain.ResearchAndAnalysis;
import com.etbsms.domain.Users;
import com.etbsms.form.AgricultureAndFoodForm;
import com.etbsms.form.PageForm;
import com.etbsms.form.QueryAAFForm;
import com.etbsms.security.User;
import com.etbsms.service.IAgricultureAndFoodService;
import com.etbsms.service.ICodeCountryService;
import com.etbsms.service.ICodeLanguageService;
import com.etbsms.service.ICodePlantService;
import com.etbsms.service.IFilesService;
import com.etbsms.service.IRecNumberService;
import com.etbsms.service.IResearchAndAnalysisService;
import com.etbsms.util.Constants;
import com.etbsms.util.Constants.FLOW_TYPE;

@Controller
@RequestMapping(value = "/form/**")
@SuppressWarnings("unused")
public class FormController {
	
	@Autowired
	private IAgricultureAndFoodService agricultureAndFoodService;
	
	@Autowired
	private ICodeLanguageService codeLanguageService;	

	@Autowired
	private IRecNumberService recNumberService;

	@Autowired
	private ICodeCountryService codeCountryService;	

	@Autowired
	private ICodePlantService codePlantService;	

	@Autowired
	private IFilesService filesService;	
	
	@Autowired
	private IResearchAndAnalysisService researchAndAnalysisService;	
	
	
	public ModelMap setMainMenu(ModelMap map){
		map.addAttribute("MAINMENU", Constants.MAIN_MENU_FORMS);
		return map;
	}
	
	@RequestMapping(value = "/form/page/input.htm")
	public String pageFormsInput(HttpServletRequest req, ModelMap map) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		setMainMenu(map);	
		map.addAttribute("SUBMENU", 1);		
		map.addAttribute("AgricultureAndFoodForm", new AgricultureAndFoodForm(users));	
		map.addAttribute("CodeLanguage", codeLanguageService.getAll());
		map.addAttribute("FilesForm", new Files());
		return Constants.PAGE_FORMINP;
	}
	
	@RequestMapping(value = "/form/page/research/input.htm")
	public String pageReserchInput(HttpServletRequest req, ModelMap map) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		setMainMenu(map);
		agricultureAndFoodService.changeTemporary(users);
		
		PageForm<AgricultureAndFood> pageForm = new PageForm<AgricultureAndFood>(users.getRow_per_page());		
		pageForm = agricultureAndFoodService.getOwnForms(users,pageForm,true);
		map.addAttribute("PageForm", pageForm);				
		map.addAttribute("SUBMENU", 4);		
		
		map.addAttribute("ResearchAndAnalysisForm", new ResearchAndAnalysis());	
		return Constants.PAGE_REAAINP;
	}
	
	/**/
	@RequestMapping(value = "/form/research/page.htm")
	public String pageReserchInput2(PageForm<AgricultureAndFood> form, ModelMap map) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();			
		if(form.isRequery())
			agricultureAndFoodService.changeTemporary(users);		
		form = agricultureAndFoodService.getOwnForms(users,form,true);
		map.addAttribute("PageForm", form);			
		//map.addAttribute("ResearchAndAnalysisForm", new ResearchAndAnalysis());	
		return Constants.PAGE_REAAINP_LIST;
	}
	/**/
	
	@RequestMapping(value = "/form/page/research/add.htm")
	@ResponseBody
	public boolean pageReserchAdd(ResearchAndAnalysis form) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();		
		form.setUsers(users);
		form.setCreated(new Date());
		AgricultureAndFood agEntity = agricultureAndFoodService.get(form.getRec_no());
		agEntity.setResearchAndAnalysis(form);
		agEntity.setFlow(Constants.FLOW_RESA);
		return agricultureAndFoodService.update(agEntity);
	}
	
	@RequestMapping(value = "/form/page/select.htm")
	public String pageFormsSelect(HttpServletRequest req, ModelMap map) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		setMainMenu(map);	
		map.addAttribute("SUBMENU", 2);
		map.addAttribute("CodeLanguage", codeLanguageService.getAll());
		map.addAttribute("FormUsers", agricultureAndFoodService.getInputUsers());
		
		QueryAAFForm form = new QueryAAFForm(users.getRow_per_page());
		form.setFlow(Constants.FLOW_KENI);
		map.addAttribute("QueryAAFForm", form);
		return Constants.PAGE_FORMSEL;
	}
	
	@RequestMapping(value = "/form/page/own.htm")
	public String pageFormsOwn(HttpServletRequest req, ModelMap map) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		setMainMenu(map);		
		PageForm<AgricultureAndFood> pageForm = new PageForm<AgricultureAndFood>(users.getRow_per_page());		
		pageForm = agricultureAndFoodService.getOwnForms(users,pageForm,false);
		map.addAttribute("SUBMENU", 3);
		map.addAttribute("PageForm", pageForm);		
		return Constants.PAGE_FORMOWN;
	}	
	
	@RequestMapping(value = "/form/page/own/list.htm")
	public String pageFormsOwnList(PageForm<AgricultureAndFood> form, ModelMap map) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();		
		form = agricultureAndFoodService.getOwnForms(users,form,false);		
		form.setRequery(false);
		map.addAttribute("PageForm", form);				
		return Constants.PAGE_FORMOWNLST;
	}
	
	@RequestMapping(value = "/form/page/own/form.htm")
	public String pageFormsOwnView(int seq_no,int state ,ModelMap map) {
		/**
		 * state = 1 , view
		 * state = 2 , edit
		 * state = 3 , view , can't edit
		 */
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();		
		AgricultureAndFood entity =	agricultureAndFoodService.get(seq_no);
		AgricultureAndFoodForm form = new AgricultureAndFoodForm(entity);
		
		map.addAttribute("CodeLanguage", codeLanguageService.getAll());
		map.addAttribute("AgricultureAndFoodForm", form);	
		map.addAttribute("STATE", state);	
		return Constants.PAGE_FORMOWNVEW;
	}	
	
	@RequestMapping(value = "/form/add.htm")
	@ResponseBody
	public String formAdd(AgricultureAndFoodForm form) {				
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		AgricultureAndFood entity = new AgricultureAndFood(form);		
		Set<CodeCountry> countrySet = new HashSet<CodeCountry>();
		for(String code : form.getCountries_code().split(",")){
			CodeCountry _code = codeCountryService.get(code);
			if(_code != null)
				countrySet.add(_code);
		}
		entity.setCountries(countrySet);				
		Set<CodePlant> plantSet = new HashSet<CodePlant>();
		for(String code : form.getPlants_code().split(",")){
			CodePlant _code = codePlantService.get(code);
			if(_code != null)
				plantSet.add(_code);
		}
		entity.setPlants(plantSet);		
		
		Set<Files> files = new HashSet<Files>();
		for(String _files : form.getFiles().split(",")){
			if(_files.length() != 0){
				//System.out.println("flies >" + _files);
				files.add(filesService.get(Integer.parseInt(_files)));
			}
		}
		
		entity.setFiles(files);		
		entity.setUsers(users);
		entity.setLanguage(codeLanguageService.get(form.getLanguage()));
		String rec_no = recNumberService.getNextRecNumber();
		entity.setRec_no(rec_no);			
		
		/*****************************************************************************************************/
		boolean saveSeccess = agricultureAndFoodService.save(entity);
		String _now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String errorCode = users.getSeq_no() + new SimpleDateFormat("MMddHHmmss").format(new Date());		
		String _saveSeccess = saveSeccess ? "成功" : "失敗";
		String returnCode = saveSeccess ? rec_no : errorCode;
		
		String _files = "";
		for(String _file : form.getFiles().split(","))
			_files += _file + ",";
		
		String _plants = "";
		for(String code : form.getPlants_code().split(","))
			_plants += code + ",";
		
		String _contries = "";
		for(String code : form.getCountries_code().split(","))
			_contries += code + ",";
			
		
		String header = "*****表單新增"+_saveSeccess+"("+_now+")["+errorCode+"]***************************************** ";
		String footer = "*********************************************************************************** ";
		StringBuffer sb = new StringBuffer();
		sb.append(header + "\n資料編號:");
		sb.append(rec_no + "\n原文標題:");
		sb.append(form.getTitle_o() + "\n作者:");
		sb.append(form.getAuthor() + "\n作者服務機構:");
		sb.append(form.getAffiliation() + "\n出版機構:");
		sb.append(form.getPublisher() + "\n期刊名稱:");
		sb.append(form.getJournal() + "\n卷期頁碼:");
		sb.append(form.getVol_page() + "\n出版年:");
		sb.append(form.getYear() + "\n語文:");
		sb.append(form.getLanguage() + "\n資料類型:");
		sb.append(form.getDoc_type() + "\n文獻性質:");
		sb.append(form.getLiterature() + ":" + form.getLiterature_desc() + "\n原文摘要:");
		sb.append(form.getAbstract_o() + "\n關鍵詞:");
		sb.append(form.getKeyword_o() + "\n原文網址:");
		sb.append(form.getUrl() + "\n原文:");
		sb.append(_files + "\n探討植物別:");
		sb.append(_plants + "\n探討國別:");
		sb.append(_contries + "\n主題分類:");
		sb.append(form.getClazz() + "\n研析資料:");
		sb.append(form.isAnalyzed() + "\n");
		sb.append(footer);
		System.out.println(sb);
		/*****************************************************************************************************/			
		return returnCode;
	}
	
	@RequestMapping(value = "/form/edit.htm")
	@ResponseBody
	public boolean formEdit(AgricultureAndFoodForm form) {
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		AgricultureAndFood entity = agricultureAndFoodService.get(form.getSeq_no());
		entity.update(form);

		Set<CodeCountry> countrySet = new HashSet<CodeCountry>();
		for(String code : form.getCountries_code().split(",")){
			CodeCountry _code = codeCountryService.get(code.trim());
			if(_code != null)
				countrySet.add(_code);
		}
		entity.setCountries(countrySet);				
		Set<CodePlant> plantSet = new HashSet<CodePlant>();
		for(String code : form.getPlants_code().split(",")){
			CodePlant _code = codePlantService.get(code.trim());
			if(_code != null)
				plantSet.add(_code);
		}
		entity.setPlants(plantSet);		
		Set<Files> files = new HashSet<Files>();
		for(String _files : form.getFiles().split(",")){
			if(_files.length() != 0)
				files.add(filesService.get(Integer.parseInt(_files)));
		}
		entity.setFiles(files);		
		entity.setLanguage(codeLanguageService.get(form.getLanguage()));
		entity.setUpdated(new Date());
		return agricultureAndFoodService.update(entity);
	}
	
	@RequestMapping(value = "/form/code/country/query.htm")
	public String codeCountryQuery(ModelMap map,String qr,String region, boolean isInit, String countriesCode,String countriesNameCh) {				
		countriesCode = countriesCode == null ? "" : countriesCode;		
		List<CodeCountry> list = codeCountryService.query(isInit ? "" : qr);		
		Map<CodeCountry,List<CodeCountry>> codeCountryMap = 
				new LinkedHashMap<CodeCountry,List<CodeCountry>>();		
		CodeCountry parent = new CodeCountry();		
		for(CodeCountry _c : list){
			_c.setSelected(countriesCode.indexOf(_c.getCode()) != -1);
			
			List<CodeCountry> _clist = null;
			if(!isCountryEquals(parent,_c.getParent())){
				_clist = new ArrayList<CodeCountry>();				
				parent = _c.getParent();
				if(!isInit)
					parent.setHide(region.indexOf(_c.getParent().getCode()) == -1);				
			}else
				_clist = codeCountryMap.get(_c.getParent());						
			_clist.add(_c);
			codeCountryMap.put(_c.getParent(),_clist);
		}		
		map.addAttribute("CodeCountryMap",codeCountryMap);
		map.addAttribute("CodeCountriesCodeSelected",countriesCode);	
		map.addAttribute("CodeCountriesNameChSelected",countriesNameCh);			
		return Constants.PAGE_CODECOUNTRY;
	}
	
	@RequestMapping(value = "/form/code/plant/query.htm")
	public String codePlantQuery(ModelMap map,String qr,String name_ch, boolean isInit, String plantsSelected) {		
		plantsSelected = plantsSelected == null ? "" : plantsSelected;		
		List<CodePlant> list = codePlantService.query(isInit ? "" : qr);		
		Map<CodePlant,List<CodePlant>> codePlantMap = 
				new LinkedHashMap<CodePlant,List<CodePlant>>();		
		CodePlant parent = new CodePlant();		
		for(CodePlant _c : list){
			_c.setSelected(plantsSelected.indexOf(_c.getCode()) != -1);
			
			List<CodePlant> _clist = null;
			if(!isPlantEquals(parent,_c.getParent())){
				_clist = new ArrayList<CodePlant>();				
				parent = _c.getParent();
			}else
				_clist = codePlantMap.get(_c.getParent());						
			_clist.add(_c);
			codePlantMap.put(_c.getParent(),_clist);
		}		
		map.addAttribute("CodePlantMap",codePlantMap);
		map.addAttribute("CodePlantsSelected",plantsSelected);		
		map.addAttribute("CodePlantsSelectedNameCH",name_ch);		
		return Constants.PAGE_CODEPLANT;
	}
	
	private static boolean isCountryEquals(CodeCountry c1,CodeCountry c2){
		boolean result = false;
		try{
			result = c1.getCode().equals(c2.getCode());
		}catch(Exception e){}
		return result;
	}
	
	private static boolean isPlantEquals(CodePlant c1,CodePlant c2){
		boolean result = false;
		try{
			result = c1.getCode().equals(c2.getCode());
		}catch(Exception e){}
		return result;
	}
	
	/*
	@RequestMapping(value = "/form/files/upload2.htm")
	@ResponseBody
	public void upload(HttpServletRequest request, HttpServletResponse response){		
		
	}
	*/
	
	@RequestMapping(value = "/form/files/upload.htm")	
	@ResponseBody
	public String qhrst(Files entity,HttpServletRequest req){
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();
		/**
		 * 判斷 os 為 windows 或linux 版本 
		 */
		String path = null;
		/*  為windows 版本*/
		if(System.getProperty("file.separator").equals("\\")){
			path = req.getServletContext().getInitParameter("file_path_wm");
		}
		/*  為linux 版本*/
		else if(System.getProperty("file.separator").equals("/")){
			path = req.getServletContext().getInitParameter("file_path_linux");
		}
		entity.setRoot_folder(path);
		entity.setUpdate_user(users.getSeq_no());
		filesService.save(entity);		
		
		String seq = String.valueOf(entity.getSeq_no());
		String name = entity.getOriginal_name().replaceAll(":", "：");
		String size = String.valueOf(entity.getSize());
		//System.out.println("--> " + seq + ":" + name + ":" + size);
		return seq + ":" + name + ":" + size;
	}
	
	/***
	 * 比對重覆值
	 * @param title_o
	 * @param author
	 * @return
	 */
	@RequestMapping(value = "/form/comparison.htm")	
	@ResponseBody
	public String comparison(String title_o, String author){
//		System.out.println("1>" + title_o);
//		System.out.println("2>" + author);
		String rec_no = agricultureAndFoodService.comparison(title_o, author);
		return (rec_no == null) ? "" : rec_no;
	}
	
	
	@RequestMapping(value = "/form/preview.htm")	
	public String preview(@RequestParam(value="rec_no")String rec_no,ModelMap map){
		try{
			System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
			Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();			
			AgricultureAndFood entity = agricultureAndFoodService.get(rec_no);
			AgricultureAndFoodForm form = new AgricultureAndFoodForm(entity);	
			map.addAttribute("AgricultureAndFoodForm", form);
			return Constants.PAGE_FORMPREVEW;
		}catch(Exception e){
			return "index";
		}
	}
	
	@RequestMapping(value = "/form/query.htm")	
	public String query(QueryAAFForm form,ModelMap map){	
		System.out.println("> " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());	
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();	
		if(form.getQuery_type() == 0){
			if(!form.isRequery()){			
				form.setLanguage(form.getLanguageStr().split(","));
				form.setDoc_type(form.getDoc_typeStr().split(","));
				form.setClazz(form.getClazzStr().split(","));
			}	
			form = agricultureAndFoodService.query(form,FLOW_TYPE.ge);		
		}		
		
		else if(form.getQuery_type() == 1){			
			if(form.getRec_no().matches("[0-9-\\s,]*")){
				System.out.println("> " + form.getFlow());
				form = agricultureAndFoodService.recNo_query(form, FLOW_TYPE.ge);
			}
		}
		
		map.addAttribute("QueryAAFForm", form);	
		map.addAttribute("CodeLanguage", codeLanguageService.getAll());
		return Constants.PAGE_FORMSELLST;
	}
}
